﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace KaoShiServer
{
    public partial class ServerWin : Form
    {
        public ServerWin()
        {
            InitializeComponent();
        }

        private void ServerWin_Load(object sender, EventArgs e)
        {
            //开始线程 ，启动Socket
            Thread thread = new Thread(SocketServer);
            thread.IsBackground = true;
            thread.Start();
        }

        private delegate void ShowStr();
        public void SocketServer()
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            IPEndPoint ipPoint = new IPEndPoint(ip, 8989);

            Socket sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sSocket.Bind(ipPoint);
            sSocket.Listen(10);

            Console.WriteLine("监听已经打开，请等待");
            while (true)
            {
                Socket listener = sSocket.Accept();
                //更新到界面
                //lbShow.Invoke(new Action(() => );
                ShowStr myDelegate = () =>
                { lbShow.Items.Insert(0, "连接成功"); };
                lbShow.Invoke(myDelegate);

                byte[] byts = new byte[512000];//4MB

                //更新到界面
                var receiveRes = listener.Receive(byts, byts.Length, SocketFlags.None);
                //字节转换成字符串
                string strReceive = Encoding.UTF8.GetString(byts);
                myDelegate = () =>
                { lbShow.Items.Insert(0, strReceive); };
                lbShow.Invoke(myDelegate);
                string strSend = "接收成功" + DateTime.Now;
                //字符串转换成字节发送
                var sendRes = listener.Send(Encoding.UTF8.GetBytes(strSend));
                listener.Close();
            }
        }


    }
}
